
import subprocess
import pandas as pd
import os
import plotly.express as px



with open("protocol.config", "r") as f:
    protocols = f.readlines()
with open("mat.config", "r") as f:
    mats = f.readlines()

res_protocol = []
for i, p in enumerate(protocols):
    if p.startswith('#'):
        continue
    res_protocol.append(i)
    script = f"""
    set protocol [list {p[:-1]}]
    wipe
    wipeAnalysis
    model BasicBuilder -ndm 1 -ndf 1
    node 0 0.
    fix 0 1
    node 1 0.
    """
    for j, m in enumerate(mats):
        if m.startswith("#"):
            continue
        script += f"""
        uniaxialMaterial DowelType {j+1} {m[:-1]}
        element twoNodeLink {j+1} 0 1 -mat {j+1} -dir 1
        """
    script += f"""
    recorder Element -file out/result{i}.out -eleRange 1 10000 material 1 stressStrain
    """
    script += """
    timeSeries Linear 1
    pattern Plain 1 1 {
        load 1 1.
    }
    constraints Plain
    numberer Plain
    system BandGeneral
    test EnergyIncr 1.0e-6 200
    algorithm Newton
    integrator LoadControl 1.
    analysis Static
    set currentdisp 0.
    set maxstep 0.1
    foreach target $protocol {
        while {$target > $currentdisp} {
            if {[expr $currentdisp + $maxstep] >= $target} {
                set step [expr $target - $currentdisp]
            } else {
                set step $maxstep
            }
            integrator DisplacementControl 1 1 $step
            set ok [analyze 1]
            if {$ok != 0} {
                return
            }
            set currentdisp [expr $currentdisp + $step]
        }
        while {$target < $currentdisp} {
            if {[expr $currentdisp - $maxstep] <= $target} {
                set step [expr $target - $currentdisp]
            } else {
                set step [expr -$maxstep]
            }
            integrator DisplacementControl 1 1 $step
            set ok [analyze 1]
            if {$ok != 0} {
                return
            }
            set currentdisp [expr $currentdisp + $step]
        }
    }"""
    print(f"Testing protocol {i}")
    res = subprocess.run("opensees", input=script, universal_newlines=True, stderr=subprocess.PIPE)
    print(res.stderr)

dfs = []
for i in res_protocol:
# while os.path.exists(f"out/result{i}.out"):
    if not os.path.exists(f"out/result{i}.out"):
        continue
    print(f"Reading P{i}")
    # data = np.loadtxt(f"out/result{i}.out")
    df = pd.read_csv(f"out/result{i}.out", delimiter=" ", header=None)
    os.remove(f"out/result{i}.out")
    NM = df.shape[1] // 2
    for j in range(NM):
        df0 = df.iloc[:, 2*j:2*j+2]
        df0.columns = ['Force', 'Disp']
        df0['Protocol'] = i + 1
        df0['Mat'] = j + 1
        dfs.append(df0)
    i += 1
print("Concating ...")
df = pd.concat(dfs)
print("Plotting ...")
fig = px.line(df, x="Disp", y="Force", color="Mat", animation_frame="Protocol",
              range_x=[min(df["Disp"]), max(df["Disp"])],
              range_y=[min(df["Force"]), max(df["Force"])])
fig.write_html("figures.html")
print("Figures written to 'figures.html'")